// in nodejs
// require()

// in front-end javascript you cant use require
// import
import { ethers } from "./ethers-5.1.esm.min.js"
import { abi, contractAddress } from "./constants.js"

const connectButton = document.getElementById("connectButton")
const fundButton = document.getElementById("fundButton")
const balanceButton = document.getElementById("balanceButton")
const withdrawButton = document.getElementById("withdrawButton")
connectButton.onclick = connect
fundButton.onclick = fund
balanceButton.onclick = getBalance
withdrawButton.onclick = withdraw

console.log(ethers)

async function connect() {
    if (typeof window.ethereum !== "undefined") {
        await window.ethereum.request({ method: "eth_requestAccounts" })
        connectButton.innerHTML = "Connected!"
    } else {
        connectButton.innerHTML = "Please install metamask!"
    }
}

async function getBalance() {
    const locked_contract_id = document.getElementById("contractId").value
    if (typeof window.ethereum != "undefined") {
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        const contract = new ethers.Contract(contractAddress, abi, signer)
        const res = await contract.get_locked_contract(locked_contract_id)
        console.log(res)
    }
}

async function fund() {
    //const ethAmount = document.getElementById("ethAmount").value

    const secretHash = document.getElementById("secrethash").value
    console.log(secretHash)
    //const secretHash = ethers.utils.soliditySha256(["string"], [secret])
    const value = document.getElementById("value").value
    const sender = document.getElementById("sender").value
    const recipient = document.getElementById("recipient").value
    const endTime = 7 * 24 * 60 * 60 + Math.ceil(new Date().valueOf() / 1000)

    console.log(sender, "Start Apply....")

    if (typeof window.ethereum !== "undefined") {
        // provider / connection to the blockchain
        // signer / wallet / someone with some gas
        // contract that we are interacting with
        // ^ ABI & Address
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        const contract = new ethers.Contract(contractAddress, abi, signer)
        try {
            const transactionResponse = await contract.fund(
                //value: ethers.utils.parseEther(ethAmount),
                secretHash,
                recipient,
                sender,
                endTime
            )
            await listenForTransactionMine(transactionResponse, provider)
            console.log("Done!")
        } catch (error) {
            console.log(error)
        }
    }
}

function listenForTransactionMine(transactionResponse, provider) {
    console.log("Mining ", transactionResponse.hash, "...")
    return new Promise((resolve, reject) => {
        provider.once(transactionResponse.hash, (transactionReceipt) => {
            console.log(
                "Completed with ",
                transactionReceipt.confirmations,
                " confirmations"
            )
            resolve()
        })
    })
}

async function withdraw() {
    const locked_contract_id = document.getElementById("contractId").value
    const preImage = document.getElementById("preImage").value
    if (typeof window.ethereum !== "undefined") {
        console.log("Applying.....")
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        const contract = new ethers.Contract(contractAddress, abi, signer)
        try {
            const transactionResponse = await contract.withdraw(
                locked_contract_id,
                preImage
            )
            await listenForTransactionMine(transactionResponse, provider)
        } catch (error) {
            console.log(error)
        }
    }
}
